<?php
class ControllerExtensionModuleCategory extends Controller {
  public function index() {
    $this->load->language('extension/module/category');

    if (isset($this->request->get['path'])) {
      $parts = explode('_', (string)$this->request->get['path']);
    } else {
      $parts = array();
    }

    if (isset($parts[0])) {
      $data['category_id'] = $parts[0];
    } else {
      $data['category_id'] = 0;
    }

    if (isset($parts[1])) {
      $data['child_id'] = $parts[1];
    } else {
      $data['child_id'] = 0;
    }

      if (isset($parts[2])) {
        $data['third_child_id'] = $parts[2];
      } else {
        $data['third_child_id'] = 0;
      }

    $this->load->model('catalog/category');

    $this->load->model('catalog/product');

    $data['categories'] = $this->categoryChildrenData(0, '',2);

    return $this->load->view('extension/module/category', $data);
  }

    /**
     * @param $category_id
     * @param string $id_path
     * @param int $load_sub_level
     *
     * @return array
     *
     * @throws Exception
     */
    private function categoryChildrenData($category_id, $id_path = '', $load_sub_level = 0)
    {
        /** @var ModelCatalogCategory $modelCatalogCategory */
        $modelCatalogCategory = $this->loadModel('catalog/category');
        $categories = $modelCatalogCategory->getCategories($category_id);

        $categories_data = [];

        foreach ($categories as $category) {
            $filter_data = [
                'filter_category_id'  => $category['category_id'],
                'filter_sub_category' => true
            ];

            $current_path = $id_path ? $id_path . '_' . $category['category_id'] : $category['category_id'];

            $categories_data[] = [
                'category_id' => $category['category_id'],
                'name'        => $category['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
                'href'        => $this->url->link('product/category', 'path=' . $current_path),
                'column'      => $category['column'] ?: 1,
                'children'    => ($load_sub_level > 0)
                    ? $this->categoryChildrenData($category['category_id'], $current_path, $load_sub_level - 1)
                    : null,
            ];
        }

        return $categories_data;
    }
}